package com.lagou.zerocopy;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NioClientSocket {

    public static void main(String[] args) throws Exception {
        SocketChannel open = SocketChannel.open();
        open.connect(new InetSocketAddress("127.0.0.1", 6689));
        String fileName = "Python-2.7.tgz";
//        String fileName = "file.txt";
        FileInputStream inputStream = new FileInputStream(fileName);
        FileChannel fileChannel = inputStream.getChannel();

        long startTime = System.currentTimeMillis();

        int fileLen = inputStream.available();
        int writeLen = 1024 * 1024;
        int pos = 0;
        int count = 0;
        while (true) {
            count = pos + writeLen > fileLen ? fileLen - pos :  writeLen ;
            fileChannel.transferTo(pos, count, open);
            pos += writeLen;
            if (pos >= fileLen) {
                break;
            }
        }

        long endTime = System.currentTimeMillis();

        System.out.println("文件复制用时：" + (endTime - startTime) + ", 文件字节长度为： " + inputStream.available());

        fileChannel.close();
        inputStream.close();
        open.close();
    }
}
